package com.example.LibrarySystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.LibrarySystem.mapper.UserMapper;
import com.example.LibrarySystem.pojo.User;
import com.example.LibrarySystem.response.Result;
import com.example.LibrarySystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String account, String password) {
        User user = userMapper.getUserByUsernameAndPassword(account, password);
        return user;
    }

    @Override
    public int insert(User user) {
        return userMapper.insert(user);
    }

    @Override
    public int update(User user) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", user.getId());
        int res = userMapper.update(user, queryWrapper);
        return res;
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    @Override
    public IPage<User> getUserByAll(Map<String, String> data) {
        int start = data.containsKey("start") ? Integer.parseInt(data.get("start")) : 1;
        int pages = data.containsKey("pages") ? Integer.parseInt(data.get("pages")) : 10;

        System.out.println("start:" + start);
        System.out.println("pages:" + pages);

        IPage<User> userIPage = new Page<>(start, pages);

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        if (data.containsKey("name") && !"".equals(data.get("name"))) {
            queryWrapper.like("name", data.get("name"));
        }

        if (data.containsKey("classId") && !"".equals(data.get("classId")) && !"全部".equals(data.get("classId"))) {
            queryWrapper.eq("class_id", Integer.parseInt(data.get("classId")));
        }

        IPage<User> res = userMapper.selectPage(userIPage, queryWrapper);
        return res;
    }
}
